import 'package:flutter/material.dart';
import '../../services/data_service.dart';
import '../ingredient_detail_screen.dart';  // 添加这一行

class CategoryTab extends StatefulWidget {
  const CategoryTab({super.key});

  @override
  State<CategoryTab> createState() => _CategoryTabState();
}

class _CategoryTabState extends State<CategoryTab> {
  int selectedIndex = 0;
  late List<String> categories;
  String searchQuery = '';
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    categories = DataService.getCategories();
  }

  Future<void> _refreshData() async {
    setState(() => isLoading = true);
    await Future.delayed(const Duration(seconds: 1)); // 模拟网络请求
    setState(() => isLoading = false);
  }

  List<dynamic> _getFilteredIngredients() {
    final ingredients = DataService.getIngredientsByCategory(categories[selectedIndex]);
    if (searchQuery.isEmpty) return ingredients;
    return ingredients.where((ingredient) => 
      ingredient.name.toLowerCase().contains(searchQuery.toLowerCase()) ||
      ingredient.description.toLowerCase().contains(searchQuery.toLowerCase())
    ).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('分类'),
        elevation: 0,
      ),
      body: Column(
        children: [
          // 搜索栏
          Padding(
            padding: const EdgeInsets.all(16),
            child: TextField(
              decoration: InputDecoration(
                hintText: '搜索配料...',
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
                filled: true,
                fillColor: Colors.grey[100],
              ),
              onChanged: (value) => setState(() => searchQuery = value),
            ),
          ),
          Expanded(
            child: Row(
              children: [
                // 左侧菜单
                Container(
                  width: 100,
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    border: Border(
                      right: BorderSide(color: Colors.grey[300]!, width: 1),
                    ),
                  ),
                  child: ListView.builder(
                    itemCount: categories.length,
                    itemBuilder: (context, index) {
                      final isSelected = selectedIndex == index;
                      return AnimatedContainer(
                        duration: const Duration(milliseconds: 300),
                        decoration: BoxDecoration(
                          color: isSelected ? Colors.white : Colors.transparent,
                          border: Border(
                            left: BorderSide(
                              color: isSelected ? Theme.of(context).primaryColor : Colors.transparent,
                              width: 4,
                            ),
                          ),
                        ),
                        child: ListTile(
                          selected: isSelected,
                          title: Text(
                            categories[index],
                            style: TextStyle(
                              color: isSelected ? Theme.of(context).primaryColor : Colors.black87,
                              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                          onTap: () {
                            setState(() {
                              selectedIndex = index;
                              searchQuery = '';
                            });
                          },
                        ),
                      );
                    },
                  ),
                ),
                // 右侧内容
                Expanded(
                  child: RefreshIndicator(
                    onRefresh: _refreshData,
                    child: AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      child: Stack(
                        children: [
                          GridView.builder(
                            key: ValueKey<String>('$selectedIndex$searchQuery'),
                            padding: const EdgeInsets.all(16),
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 1.5,
                              crossAxisSpacing: 16,
                              mainAxisSpacing: 16,
                            ),
                            itemCount: _getFilteredIngredients().length,
                            itemBuilder: (context, index) {
                              final ingredient = _getFilteredIngredients()[index];
                              return Hero(
                                tag: 'ingredient_${ingredient.name}',
                                child: Material(
                                  child: Card(
                                    elevation: 4,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: InkWell(
                                      onTap: () {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                            builder: (context) => IngredientDetailScreen(
                                              ingredient: ingredient,
                                            ),
                                          ),
                                        );
                                      },
                                      borderRadius: BorderRadius.circular(12),
                                      child: Padding(
                                        padding: const EdgeInsets.all(12),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              children: [
                                                TweenAnimationBuilder(
                                                  duration: const Duration(milliseconds: 500),
                                                  tween: Tween<double>(begin: 0, end: 1),
                                                  builder: (context, double value, child) {
                                                    return Opacity(
                                                      opacity: value,
                                                      child: Container(
                                                        width: 48,
                                                        height: 48,
                                                        decoration: BoxDecoration(
                                                          color: Colors.grey[200],
                                                          borderRadius: BorderRadius.circular(8),
                                                        ),
                                                        child: const Icon(Icons.food_bank, size: 32),
                                                      ),
                                                    );
                                                  },
                                                ),
                                                const SizedBox(width: 12),
                                                Expanded(
                                                  child: Text(
                                                    ingredient.name,
                                                    style: const TextStyle(
                                                      fontSize: 16,
                                                      fontWeight: FontWeight.bold,
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            const SizedBox(height: 8),
                                            Expanded(
                                              child: Text(
                                                ingredient.description,
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  color: Colors.grey[600],
                                                  fontSize: 14,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                          if (isLoading)
                            Container(
                              color: Colors.white.withOpacity(0.8),
                              child: const Center(
                                child: CircularProgressIndicator(),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}